package edu.testdemo.controller;

import edu.nf.beans.annotations.Component;
import edu.nf.beans.annotations.Inject;
import edu.nf.web.ActionContext;
import edu.nf.web.FrameworkServlet;
import edu.nf.web.ViewResult;
import edu.nf.web.annotation.RequestMapping;
import edu.nf.web.map.RequestMap;
import edu.nf.web.view.DefaultViewResult;
import edu.nf.web.view.ForwardView;
import edu.nf.web.view.JsonView;
import edu.testdemo.dto.ValueDto;
import edu.testdemo.exception.LoginException;
import edu.testdemo.model.Users;
import edu.testdemo.service.LoginService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Component("userController")
public class UserController extends BasicController{

    @Inject(name = "loginService")
    private LoginService service;

    @RequestMapping("/login")
    public ViewResult login(String userName,String password){
        Users user = new Users();
        user.setUserName(userName);
        user.setPassword(password);
        ValueDto dto = new ValueDto();
        try {
            user = service.login(user);
            ActionContext.getContext().getSession().put("user", user);
            dto = successJson(user);
        } catch (LoginException e) {
            dto = errorJson(500,e.getMessage());
        }
        return new JsonView(dto);
    }

    /*@RequestMapping("/select")
    public ViewResult select(String id){
        Users user = service.select(Integer.parseInt(id));
        System.out.println(user.getUserName());
        HttpServletRequest request = (HttpServletRequest)ActionContext.getContext().getRequest().get(FrameworkServlet.REQUEST);
        request.setAttribute("user",user);
        return new ForwardView("login.jsp");
    }*/

    @RequestMapping("/getAllUsers")
    public ViewResult getAllUsers(){
        List<Map<String, Object>> allUsers = service.getAllUsers();
        ValueDto dto = new ValueDto();
        try {
            dto = successJson(allUsers);
        } catch (LoginException e) {
            dto = errorJson(500,e.getMessage());
        }
        return new JsonView(dto);
    }

    @RequestMapping("/deleteUsers")
    public void deleteUsers(String uid){
        int id = Integer.parseInt(uid);
        try {
            service.deleteUsers(id);
        } catch (Exception e) {
            errorJson(500,"delete users fail...");
        }
    }


    @RequestMapping("/updateUsers")
    public void updateUsers(String uid){
        int id = Integer.parseInt(uid);
        try {
            service.updateUsers(id);
        } catch (Exception e) {
            errorJson(500,"update users fail...");
        }
    }
}
